
from amscms import settings
from amscms.ams.models import AdStats, Advertizer, Ad
from amscms.core.forms import UserSignupForm
from amscms.core.utils import navigation
from amscms.core.utils.email import send_email
from amscms.core.utils.request import render_to_response
from amscms.recaptcha_works.decorators import fix_recaptcha_remote_ip
from codecs import open
from django.contrib import messages
from django.contrib.auth.models import User
from django.contrib.auth.tokens import default_token_generator
from django.contrib.auth.views import logout
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponse
from django.template.loader import render_to_string
from django.utils.http import base36_to_int
from django.utils.translation import ugettext as _
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
import os

"""
The index page of the AMS module/web application
"""
def index(request):
    context = {}
    # We changed the index
    #tags = Term.objects.find_popular_terms()
    #tags_cloud = Term.objects.prepare_importance_cloud(tags)
    #top_ads = Ad.objects.find_top_ads()
    #context["tags"] = tags_cloud
    #if len(top_ads) == 0:
    #    context["ad"] = None
    #else:
    #    context["ad"] = top_ads[0]["ad"]
    return render_to_response(request, "index.html", context)

def global_stats(request):
    context = {}
    top_investors = Advertizer.objects.find_top_investor_advertizers()
    top_registrars = Advertizer.objects.find_top_registrar_advertizers()
    context["total_registered_ads"] = Ad.objects.find_registered_ads_count()
    context["total_published_ads"] = Ad.objects.find_published_ads_count()
    context["total_ad_views"] = AdStats.objects.find_total_ad_views()
    if len(top_investors) == 0:
        context["top_investor"] = ""
        context["top_investor_total"] = "0"
    else:
        context["top_investor"] = top_investors[0]["advertizer"]
        context["top_investor_total"] = top_investors[0]["total"]
    if len(top_registrars) == 0:
        context["top_registrar"] = ""
        context["top_registrar_total"] = "0"
    else:
        context["top_registrar"] = top_registrars[0]["advertizer"]
        context["top_registrar_total"] = top_registrars[0]["total"]
    return context

def sitemap(request):
    result = render_to_string("sitemap.xml", {})
    return HttpResponse(result, mimetype="plain/text", content_type="application/xml")

def google_verif(request):
    result = render_to_string(settings.GOOGLE_VERIF_HTML, {})
    return HttpResponse(result, mimetype="plain/text", content_type="plain/text")

def update_global_stats(request):
    stats = global_stats(request)
    result = render_to_string('stats_template.html', stats)
    stats_path = os.path.join(settings.SITE_ROOT, 'ams/templates/stats.html')
    open(stats_path, "w", "utf-8").write(result)
    if request is not None:
        return render_to_response(request, "stats.html", stats)
    pass

def core_logout(request):
    return logout(request, next_page="/")

@fix_recaptcha_remote_ip
@csrf_protect
def signup(request, template_name="registration/signup.html"):
    navigation.breadcrumb(request, 'signup')
    if request.method == "POST":
        form = UserSignupForm(data=request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, _("Sign Up was successful."))
            return HttpResponseRedirect("/core/signup/done/")
    else:
        form = UserSignupForm()
    context = {}
    context['form'] = form
    return render_to_response(request, template_name, context)

def signup_done(request, template_name="registration/signup_done.html"):
    return render_to_response(request, template_name)

# Doesn't need csrf_protect since no-one can guess the URL
@never_cache
def signup_active(request, uidb36=None, token=None,
                  post_activation_redirect=None,
                  token_generator=default_token_generator,
                  domain_override=None, use_https=False):
    """
    View that checks the hash in a account activation link and activates a 
    related user account 
    """
    assert uidb36 is not None and token is not None
    if post_activation_redirect is None:
        post_activation_redirect = reverse('amscms.core.views.signup_active_done')
    try:
        uid_int = base36_to_int(uidb36)
        user = User.objects.get(id=uid_int)
    except (ValueError, User.DoesNotExists):
        user = None
    
    if user is not None and token_generator.check_token(user, token):
        user.is_active = True
        user.save()
        """
        Sends successful email to the user. 
        """
        if not domain_override:
            current_site = Site.objects.get_current()
            site_name = current_site.name
            domain = current_site.domain
        else:
            site_name = domain = domain_override
        c = {
            'subject': _(u"Registration was successful on %(site_name)s" % {'site_name': site_name, }),
            'site_name': site_name,
            'user': user,
            'domain': domain,
            'protocol': use_https and 'https' or 'http',
            'login_url': reverse('django.contrib.auth.views.login'),
        }
        send_email(user.email, c, settings.DEFAULT_FROM_EMAIL,
                   "registration/signup_email_activated.txt",
                   "registration/signup_email_activated.html")
        
    else:
        messages.error(request, _(u"Invalid activation link, you may already activated, try to login. "))
        return HttpResponseRedirect("/")
    return HttpResponseRedirect(post_activation_redirect)
    
def signup_active_done(request, template_name="registration/signup_active_done.html"):
    return render_to_response(request, template_name);
